package com.ruoyi.web.controller.tech;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.Technician;
import com.ruoyi.system.service.ITechnicianService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Anonymous  //此注解是不加权限直接可以调用该类的所有接口
@RestController
@CrossOrigin(origins = "*")  //这里是解决前端跨域的问题
@RequestMapping("/api")
public class HtmlController extends BaseController {

    private static Logger log = LoggerFactory.getLogger(HtmlController.class);

    @Autowired
    private ITechnicianService technicianService;

    //列表
    //http://127.0.0.1:9070/api/list
    @PostMapping("/list")
    public AjaxResult list(@Validated @RequestBody Technician technician) {
        List<Technician> list = technicianService.selectList(technician);
        logger.info("官网数据:{}", JSONObject.toJSONString(list));
        return success(list);
    }

    //http://127.0.0.1:9070/api/30
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return success(technicianService.selectTechnicianById(id));
    }

    //http://127.0.0.1:9070/api/upload
    @PostMapping("/upload")
    public AjaxResult uploadTechnician(
            @RequestParam String name,
            @RequestParam String phone,
            @RequestParam(required = false) String message,
            @RequestParam MultipartFile mainImg,
            @RequestParam MultipartFile listImg) {

        // 文件类型校验
        if (!isValidImage(mainImg) || !isValidImage(listImg)) {
            return AjaxResult.error("只允许上传JPG/PNG图片");
        }

        try {
            // 1. 获取标准化上传路径
            String uploadRoot = RuoYiConfig.getTechnicianUploadPath2();

            // 2. 创建日期目录
            String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            Path targetDir = Paths.get(uploadRoot, datePath);

            if (!Files.exists(targetDir)) {
                Files.createDirectories(targetDir);
            }

            // 3. 生成随机文件名（保留原始扩展名）
            String mainImgName = generateFileName(mainImg);
            String listImgName = generateFileName(listImg);

            // 4. 存储文件
            Path mainImgPath = targetDir.resolve(mainImgName);
            Path listImgPath = targetDir.resolve(listImgName);

            mainImg.transferTo(mainImgPath);
            listImg.transferTo(listImgPath);

            // 5. 构建数据库存储路径（相对路径）
            String dbMainPath = "technician2/" + datePath + "/" + mainImgName;
            String dbListPath = "technician2/" + datePath + "/" + listImgName;

            // 6. 保存到数据库（示例）
            Technician tech = new Technician();
            tech  .setName(name);
            tech .setPhone(phone);
            tech .setMessage(message);
            tech .setMainImg(dbMainPath);
            tech .setListImg(dbListPath);

            technicianService.insertTechnician(tech);

            Map<String, String> resultData = new HashMap<>();
            resultData.put("mainUrl", "/technician2/" + datePath + "/" + mainImgName);
            resultData.put("listUrl", "/technician2/" + datePath + "/" + listImgName);

            return AjaxResult.success("上传成功", resultData);

        } catch (IOException e) {
            log.error("文件上传失败", e);
            return AjaxResult.error("文件上传失败：" + e.getMessage());
        }
    }

    // 辅助方法：生成随机文件名
    private String generateFileName(MultipartFile file) {
        return UUID.randomUUID() +
                getFileExtension(file.getOriginalFilename());
    }

    // 辅助方法：图片校验
    private boolean isValidImage(MultipartFile file) {
        String contentType = file.getContentType();
        return contentType != null &&
                (contentType.startsWith("image/jpeg") ||
                        contentType.startsWith("image/png"));
    }

    // 获取文件扩展名
    private String getFileExtension(String filename) {
        return filename.substring(filename.lastIndexOf("."));
    }


}
